<template>
  <div>
    <a-card>
      <div ref="pieChart1" :style="{width:'100%',height:'368px'}"></div>
      <div ref="lineChart1" :style="{width:'100%',height:'368px'}"></div>
    </a-card>
  </div>
</template>
<script>

import { getAction } from '@/api/manage'
export default
{
  name: 'sleep',
  data() {
    return {
      url: {
        list: '/health/sleep/sleepReport'
      },
      searchData: {
        dateType: '',
        semesterId: '',
        classId: '',
        studentId: ''
      },
      color:["#0CDF8A","#3EACE5"],
      detailData: {},
      numList:[]
    }
  },
  props:["dataForm","monthName","className"],
  components: {},
  filters: {},
  
  computed: {},
  
  created() {
  },
  
  activated() {
  },

  mounted() {
    this.load()
  },

  methods: {
    load() {
      this.numList = []
      const dataForm = this.dataForm
      // 查询列表数据
      this.searchData.dateType = dataForm.dateType == 'historySem' ? 'sem' : dataForm.dateType
      this.searchData.semesterId = dataForm.semesterId ? dataForm.semesterId : dataForm.semesterHistoryId
      this.searchData.classId = dataForm.classId ? dataForm.classId : undefined
      this.searchData.studentId = dataForm.studentId ? dataForm.studentId : undefined
      this.searchData.startDate = dataForm.startDate;
      this.searchData.endDate = dataForm.endDate;
      if(dataForm.studentId) {
        this.studentChart()
      }else if(dataForm.classId) {
        this.classChart();
      }else{
        this.allChart();
      }
    },
    allChart() {
      // 查询运动数据
      let params = {
        dateType: 'month',
        queryType: 'school',
        queryDate: this.searchData.startDate,
        semesterId: this.searchData.semesterId
      }
      getAction(this.url.list, params).then((res)=>{
        if(res.success){
          //饼图
          this.detailData = res.result.count[0];
          this.getPieAndLineData(this.detailData);

          // 各班平均
          var categorys = [];
          var xData = [];//平均睡眠时长
          const classList = this.dataForm.classList.filter(item => { return item.id != ''});
          classList.forEach(el => {
            categorys.push(el.className);

            const classData = res.result.report.find(item => item.name == el.className)
            classData.average = classData.average ? parseFloat(classData.average).toFixed(2) : 0
            xData.push(classData.average)
          })
          this.initLineChart(this.$refs.lineChart1, '各班平均入睡时长统计', categorys, xData);
        } else {
          this.$message.warning(res.message);
        }
      }).catch(()=>{
      })
    },
    classChart() {
      // 查询运动数据
      let params = {
        dateType: 'month',
        queryType: 'class',
        queryDate: this.searchData.startDate,
        semesterId: this.searchData.semesterId,
        classId: this.searchData.classId
      }
      getAction(this.url.list, params).then((res)=>{
        if(res.success){
          //饼图
          this.detailData = res.result.count[0];
          this.getPieAndLineData(this.detailData);

          // 学生平均
          var categorys = [];
          var xData = [];//平均睡眠时长
          res.result.report.forEach(el => {
            categorys.push(el.name);
            
            if(el && el.average != null) {
              xData.push(Number(el.average).toFixed(2))
            }else{
              xData.push(0)
            }
          })
          this.initLineChart(this.$refs.lineChart1, '幼儿平均入睡时长统计', categorys, xData);
        } else {
          this.$message.warning(res.message);
        }
      }).catch(()=>{
      })
    },
    studentChart() {
      // 查询运动数据
      let params = {
        dateType: 'month',
        queryType: 'student',
        queryDate: this.searchData.startDate,
        semesterId: this.searchData.semesterId,
        classId: this.searchData.classId,
        studentId: this.searchData.studentId
      }
      getAction(this.url.list, params).then((res)=>{
        if(res.success){
          //饼图
          this.detailData = res.result.count[0];
          this.getPieAndLineData(this.detailData);

          // 每天
          const record = res.result.report[0] == null ? [] : res.result.report;
          var categorys = [];
          var xData = [];//平均睡眠时长
          const daysColums = this.dataForm.daysColums;
          for(let rowIndex = 0; rowIndex < daysColums.length; rowIndex++){
            const rowString = daysColums[rowIndex].toString();
            categorys.push(rowString.substring(8));

            const dayData = record.find(item => item.name == rowString)
            if(dayData && dayData.average){
              xData.push((Number(dayData.average)).toFixed(2))
            } else {
              xData.push(0);
            }
          }
          this.initLineChart(this.$refs.lineChart1, '每天入睡时长统计', categorys, xData);
        } else {
          this.$message.warning(res.message);
        }
      }).catch(()=>{
      })
    },
    getPieAndLineData(val) {
      let pieData = [
        {
          name: '深睡',
          value: val ? val.deepSleepDuration : 0
        },
        {
          name: '浅睡',
          value: val ? val.lightSleepDuration : 0
        },
        {
          name: '清醒',
          value: val ? val.wakefulnessDuration : 0
        }
      ];
      this.initPieChart(pieData);
    },
    initPieChart(pieData){
      let el = this.$refs.pieChart1;
      var myChartSports;
      if(this.$echarts.getInstanceByDom(el)) {
        myChartSports = this.$echarts.getInstanceByDom(el)
      }
      else{
        myChartSports = this.$echarts.init(el)
      }
      var colorList = ['#73DDFF', '#73ACFF', '#FDD56A', '#FDB36A', '#FD866A', '#9E87FF', '#58D5FF']
      let option = {
        title: {
          text: this.monthName + this.className+'午睡统计分析',
          x:'center',//水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
	        y:'top',//垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
          // top: 'center',
          // left: '42%', 
          // textAlign: 'center',
        },
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(0,0,0,0.5)',
          textStyle: {
            // 文字提示样式
            color: '#fff',
            fontSize: '12'
          },
          borderColor: 'transparent',
          formatter: '{b0}: {c0}分钟<br />占比：{d}%'
        },
        series: [
          {
            type: 'pie',
            center: ['50%', '50%'],
            radius: ['34%', '46%'],
            clockwise: true,
            avoidLabelOverlap: true,
            itemStyle: {
              normal: {
                color: function(params) {
                  return colorList[params.dataIndex]
                }
              }
            },
            emphasis: {
              scale: true,
              scaleSize: 15
            },
            label: {
              show: true,
              color: 'inherit',
              position: 'outside',
              formatter: '{a|{b}：{d}%}\n{hr|}',
              rich: {
                a: {
                  // padding: [-20, 3, -20, 3]
                },
              }
            },
            labelLine: {
              normal: {
                length: 10,
                length2: 10,
                lineStyle: {
                  width: 1
                }
              }
            },
            data: pieData
          }
        ]
      }
      myChartSports.setOption(option)
      window.addEventListener('resize', () => {
        myChartSports.resize()
      })
    },
    initLineChart(el, title, categorys, xData) {
      var myChartSports;
      if(this.$echarts.getInstanceByDom(el)) {
        myChartSports = this.$echarts.getInstanceByDom(el)
      }
      else{
        myChartSports = this.$echarts.init(el)
      }

      const legendTitle = ['睡眠时长(分钟)'];
      var optionChart = {
        title : {
          show:true,//显示策略，默认值true,可选为：true（显示） | false（隐藏）
          text: this.monthName + ' ' + this.className + title,//主标题文本，'\n'指定换行
          x:'center',//水平安放位置，默认为'left'，可选为：'center' | 'left' | 'right' | {number}（x坐标，单位px）
	        y:'top',//垂直安放位置，默认为top，可选为：'top' | 'bottom' | 'center' | {number}（y坐标，单位px）
        },
        tooltip: {
          borderColor: 'transparent',
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.5)',
          axisPointer: {
            type: 'shadow',
            label: {
              show: true,
              backgroundColor: '#333'
            }
          },
          textStyle: {
            align: 'left',
            color: '#fff',
            fontSize: '12'
          }
        },
        legend: {
          data: legendTitle,
          textStyle: {
            color: '#ccc'
          },
          // orient: 'vertical', //垂直显示 
          // y: 'top', //延Y轴居中 
          // x: 'right', //居右显示
          right: '18%'
        },
        xAxis: {
          type: 'category',
          data: categorys
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: legendTitle[0],
            data: xData,
            type: 'bar',
            barWidth: 10,
            itemStyle: {
              normal: {
                barBorderRadius: [5,5,0,0],
                color: this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: this.color[0]
                  },
                  {
                    offset: 1,
                    color: this.color[1]
                  }
                ]),
                label : {
                  show: true // 显示数据
                },
              }
            },
            smooth: true
          }
        ]
      };

      myChartSports.setOption(optionChart);
      setTimeout(() => {
        this.handleEmit()
      }, 3000);
      window.addEventListener("resize", ()=>{
        myChartSports.resize();
      })
    },
    handleEmit(){
      this.numList.push(true);
      if (this.numList.length == 2) {
        this.$emit("ok")
      }
    }
  }
}
</script>
<style scoped lang="less">
</style>